<template>
  <div id="app" class="app-container">
    <div v-if="!audioUnlocked" class="unlock-audio-tip" @click="unlockAudio">
      🔔 点击此处开启提醒音效
    </div>
    <el-container>
      <el-main>
        <router-view></router-view>
      </el-main>
      <el-footer height="50px">
        <nav class="nav-menu">
          <router-link to="/tasks" class="nav-item">
            <el-icon><List /></el-icon>
            <span>任务</span>
          </router-link>
          <router-link to="/quadrant" class="nav-item">
            <el-icon><Grid /></el-icon>
            <span>四象限</span>
          </router-link>
          <router-link to="/calendar" class="nav-item">
            <el-icon><Calendar /></el-icon>
            <span>日历</span>
          </router-link>
          <router-link to="/timer" class="nav-item">
            <el-icon><Timer /></el-icon>
            <span>计时</span>
          </router-link>
          <router-link to="/deepseek" class="nav-item">
            <el-icon><ChatDotRound /></el-icon>
            <span>AI 助手</span>
          </router-link>
        </nav>
      </el-footer>
    </el-container>
    <!-- 全局任务提醒弹窗 -->
    <el-drawer
      v-model="showReminder"
      direction="btt"
      size="auto"
      :with-header="false"
      custom-class="reminder-drawer"
    >
      <div class="reminder-drawer-content">
        <div class="reminder-time">{{ formatTime(currentTask.expectedTime) }}</div>
        <div class="reminder-desc">{{ currentTask.description }}</div>
      </div>
      <div class="reminder-drawer-footer">
        <el-button @click="focusTask" type="primary" plain size="large">开始专注</el-button>
        <el-button @click="confirmReminder" type="primary" size="large">确认</el-button>
      </div>
    </el-drawer>
    <!-- 音效播放器 -->
    <audio ref="remindAudio" src="/oclock.mp3" preload="auto"></audio>
    <!-- AI 助手浮窗 -->
    <DeepSeekFloat />
  </div>
</template>

<script>
import { List, Grid, Timer, Calendar, ChatDotRound } from '@element-plus/icons-vue'
import DeepSeekFloat from '@/components/DeepSeekFloat.vue'

export default {
  name: 'App',
  components: {
    List,
    Grid,
    Timer,
    Calendar,
    ChatDotRound,
    DeepSeekFloat
  },
  data() {
    return {
      websocket: null,
      showReminder: false,
      currentTask: {
        description: '',
        expectedTime: ''
      },
      lastMessageTime: null,
      heartbeatInterval: null,
      audioUnlocked: false
    }
  },
  mounted() {
    this.initWebSocket()
    // 监听用户首次交互，解锁音频
    // window.addEventListener('click', this.unlockAudio, { once: true })
  },
  beforeUnmount() {
    if (this.heartbeatInterval) {
      clearInterval(this.heartbeatInterval)
    }
    this.closeWebSocket()
  },
  methods: {
    initWebSocket() {
      if ('WebSocket' in window) {
        try {
          this.websocket = new WebSocket('ws://localhost:8080/api/websocket/100')
          this.heartbeatInterval = setInterval(() => {
            if (this.websocket.readyState === WebSocket.OPEN) {
              // 心跳日志
              // console.log('WebSocket连接状态检查:', this.websocket.readyState)
            }
          }, 5000)
          this.websocket.onmessage = (event) => {
            this.handleTaskMessage(event.data)
          }
          this.websocket.onclose = () => {
            if (this.heartbeatInterval) {
              clearInterval(this.heartbeatInterval)
            }
          }
        } catch (error) {
          // console.error('WebSocket错误:', error)
        }
      }
    },
    handleTaskMessage(message) {
      if (message.includes('任务提醒')) {
        try {
          const parts = message.split('，')
          const description = parts.find(part => part.includes('描述-'))?.split('描述-')[1]
          const expectedTime = parts.find(part => part.includes('预期时间-'))?.split('预期时间-')[1]
          if (description && expectedTime) {
            this.currentTask = {
              description,
              expectedTime
            }
            this.showReminder = true
            // 只有解锁后才播放音效
            if (this.audioUnlocked) {
              this.$nextTick(() => {
                if (this.$refs.remindAudio) {
                  this.$refs.remindAudio.currentTime = 0;
                  this.$refs.remindAudio.play();
                }
              })
            }
          }
        } catch (error) { /* no-op */ }
      }
    },
    confirmReminder() {
      this.showReminder = false
      this.currentTask = {
        description: '',
        expectedTime: ''
      }
      // 关闭音效
      const audio = this.$refs.remindAudio;
      if (audio) {
        audio.pause();
        audio.currentTime = 0;
      }
    },
    focusTask() {
      this.showReminder = false
      this.$router.push('/timer')
      // 关闭音效
      const audio = this.$refs.remindAudio;
      if (audio) {
        audio.pause();
        audio.currentTime = 0;
      }
    },
    closeWebSocket() {
      if (this.websocket) {
        this.websocket.close()
      }
    },
    formatTime(timeStr) {
      if (!timeStr) return ''
      try {
        let cleanStr = timeStr.replace(/([A-Z]{3,4})/g, '').replace(/\s+/g, ' ').trim()
        const months = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec']
        months.forEach(m => {
          cleanStr = cleanStr.replace(new RegExp(m, 'i'), m)
        })
        const date = new Date(cleanStr)
        if (isNaN(date.getTime())) return ''
        const h = date.getHours().toString().padStart(2, '0')
        const m = date.getMinutes().toString().padStart(2, '0')
        return `${h}:${m}`
      } catch {
        return ''
      }
    },
    unlockAudio() {
      const audio = this.$refs.remindAudio;
      if (audio) {
        audio.play().then(() => {
          audio.pause();
          audio.currentTime = 0;
          this.audioUnlocked = true;
        }).catch(() => {
          // 失败也允许用户多点几次
        });
      }
    }
  }
}
</script>

<style>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  color: #2c3e50;
}

.app-container {
  background: white;
  min-height: 100vh;
}

.el-container {
  min-height: 100vh;
  display: flex;
  flex-direction: column;
}

.el-main {
  flex: 1;
  padding: 0;
  background-color: #f5f7fa;
  overflow-x: hidden;
}

.el-footer {
  padding: 0;
  background-color: #fff;
  border-top: 1px solid #dcdfe6;
  position: fixed;
  bottom: 0;
  width: 100%;
  z-index: 100;
}

.nav-menu {
  height: 100%;
  display: flex;
  justify-content: space-around;
  align-items: center;
}

.nav-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  color: #909399;
  text-decoration: none;
  font-size: 12px;
  padding: 4px 0;
}

.nav-item .el-icon {
  font-size: 20px;
  margin-bottom: 2px;
}

.nav-item.router-link-active {
  color: #409eff;
}

.reminder-drawer {
  border-radius: 16px 16px 0 0;
  min-height: 180px;
  max-width: 600px;
  margin: 0 auto;
  padding-bottom: env(safe-area-inset-bottom, 20px);
}
.reminder-drawer-content {
  padding: 32px 24px 16px 24px;
  text-align: left;
}
.reminder-time {
  color: #409eff;
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 8px;
}
.reminder-desc {
  font-size: 22px;
  font-weight: bold;
  margin-bottom: 24px;
  word-break: break-all;
}
.reminder-drawer-footer {
  display: flex;
  justify-content: space-between;
  padding: 0 24px 24px 24px;
  gap: 16px;
}
.reminder-drawer-footer .el-button {
  flex: 1;
  font-size: 18px;
  height: 48px;
}
@media (max-width: 600px) {
  .reminder-drawer {
    max-width: 100vw;
    min-width: 0;
    padding-left: 0;
    padding-right: 0;
  }
  .reminder-drawer-content, .reminder-drawer-footer {
    padding-left: 12px;
    padding-right: 12px;
  }
}
.unlock-audio-tip {
  position: fixed;
  top: 0;
  left: 0;
  width: 100vw;
  background: #fffbe6;
  color: #d48806;
  text-align: center;
  padding: 12px 0;
  z-index: 9999;
  font-size: 16px;
  cursor: pointer;
  border-bottom: 1px solid #ffe58f;
}
</style>
